from sqlalchemy.orm import Session
from schema import Machine_schema
from model import Machine_model



def get_Machine(db: Session, ID: int):
    return db.query(Machine_model.Machine).filter(Machine_model.Machine.ID == ID).first()


def get_all_Machine(db: Session):
    return db.query(Machine_model.Machine).all()


def delete_Machine(db: Session, ID):
    to_delete = db.query(Machine_model.Machine).filter(Machine_model.Machine.ID == ID)
    deleted = to_delete.delete()
    if deleted == 0:
        return None
    else:
        db.commit()
        return True


def create_Machine(db: Session, Machine: Machine_schema.Machine):
    db_Machine = Machine_model.Machine(
        EquipmentNumber=Machine.EquipmentNumber,
        EquipmentName=Machine.EquipmentName,
        Function=Machine.Function,
        Status=Machine.Status,
        HealthStatus=Machine.HealthStatus,
        ParameterName=Machine.ParameterName,
        ParameterInfo=Machine.ParameterInfo,
        FarmID=Machine.FarmID,
    )
    db.add(db_Machine)
    db.commit()
    db.refresh(db_Machine)
    return db_Machine


def update_Machine(db: Session, ID, field_name, new_value):
    db_Machine = db.query(Machine_model.Machine).filter(Machine_model.Machine.ID == ID).first()
    setattr(db_Machine, field_name, new_value)
    db.commit()
    db.refresh(db_Machine)
    return db_Machine
